package com.xiyu.service.framework.postOffice.factory;

import com.xiyu.service.framework.exception.ServiceException;
import com.xiyu.service.framework.postOffice.service.PostOfficeService;
import com.xiyu.service.model.mailbox.account.MailboxAccount;
import com.xiyu.service.repository.mailbox.account.MailboxAccountRepository;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import java.util.Optional;

import static com.xiyu.service.errorCode.mailbox.MailErrorCode.MAILBOX_ACCOUNT_NOT_EXIST;
import static com.xiyu.service.framework.exception.util.ServiceExceptionUtil.exception;

@Component
public class PostOfficeFactory {
    @Resource
    private ApplicationContext applicationContext;

    @Resource
    private MailboxAccountRepository mailboxAccountRepository;

    public PostOfficeService getInstance(Long accountId){
        Optional<MailboxAccount> optionalAccount = mailboxAccountRepository.findById(accountId);
        if(!optionalAccount.isPresent())
            throw exception(MAILBOX_ACCOUNT_NOT_EXIST);
        MailboxAccount account = optionalAccount.get();
        return getTemplate(account);
    }

    private PostOfficeService getTemplate(MailboxAccount account) {
        try {
            String beanName = "postOfficeService";
            return (PostOfficeService) applicationContext.getBean(beanName, account);
        }catch (BeanCreationException e) {
            Throwable cause = e.getCause();
            while (cause != null) {
                if (cause instanceof ServiceException) {
                    throw (ServiceException)cause;
                }
                cause = cause.getCause();
            }
            throw e;
        }
    }


}
